package com.yqg.manage.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.yqg.manage.exception.ServiceException;
import com.yqg.manage.utils.Constants;
import com.yqg.manage.utils.JwtTokenUtil;
import com.yqg.manage.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author suzhuang
 * @ClassName: JwtInterceptor
 * @Function: TODO
 * @Date: 2023/6/26 16:09
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    JwtTokenUtil tokenUtil;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        HttpSession session = request.getSession();
        // 执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(Constants.CODE_401, "无token，请重新登录");
        }
        try {
            if (tokenUtil.canRefresh(token)) {
                redisUtil.expire(token, Constants.EXPIRATION_TIME);
                return true;
            }
        } catch (Exception e) {
            throw new ServiceException(Constants.CODE_401, "无效token，请重新登录");
        }
        return false;
    }
}

